package Store

import (
	"fmt"
	"github.com/goccy/go-json"
	"db2s/ref"
)

var Storage StorageEr


func Init() (err error) {
	Storage = NewStorage(&BadgerDb{DataDir: "dataDir"})
	if err = Storage.BaseDirInitStorage(); err != nil {
		return
	}
	var tableName []string
	for _, v := range ref.GetJSONFieldNames(TableName{}) {
		tableName = append(tableName, v)
	}
	if err = Storage.Open(tableName...); err != nil {
		return err
	}
	var qq map[string]string
	if qq, err = Query(Position, "all"); err != nil {
		return err
	}
	fmt.Println("--------datadir:", qq)
	if err = Truncate(Position); err != nil {
		return err
	}
	return
}
func Create() {
	Storage.Create()
}
func Drop(table tableTypeId) (err error) {
	return Storage.Drop(getTableTypeStr(table))
}
func Open() {
	Storage.Open()
}
func Close() (err error) {
	if err = Storage.Close(); err != nil {
		return err
	}
	return
}
func structToMapValue(expr any) (key string, res map[string]string, err error) {
	res = make(map[string]string)
	switch expr.(type) {
	case PositionInfo:
		key = expr.(PositionInfo).Key
	}
	var value []byte
	if value, err = json.Marshal(expr); err != nil {
		return
	}
	res[key] = string(value)
	return
}
func Query(table tableTypeId, key string) (result map[string]string, err error) {
	return Storage.Query(getTableTypeStr(table), key)
}
func Insert(query tableTypeId, updates any) (err error) {
	//var key string
	var _, insertValue map[string]string
	if _, insertValue, err = structToMapValue(updates); err != nil {
		return err
	}
	//if queryValue, err = Query(query, key); err != nil {
	//	return err
	//}
	//if len(queryValue) > 0 {
	//	err = fmt.Errorf("the current key %v is duplicated and the insertion failed for table %v", key, getTableTypeStr(query))
	//	return
	//}
	return Storage.Insert(getTableTypeStr(query), insertValue)
}
func Update(query tableTypeId, updates any) (err error) {
	var key string
	var queryValue, updateValue map[string]string
	if key, updateValue, err = structToMapValue(updates); err != nil {
		return err
	}
	if queryValue, err = Query(query, key); err != nil {
		return err
	}
	if len(queryValue) == 0 {
		err = fmt.Errorf("the current key %v is duplicated and the insertion failed for table %v", key, getTableTypeStr(query))
		return
	}
	return Storage.Update(getTableTypeStr(query), updateValue)
}
func Delete() {
	Storage.Delete()
}

func Truncate(query tableTypeId) (err error) {
	return Storage.Truncate(getTableTypeStr(query))
}
func Sync(query tableTypeId) (err error) {
	return Storage.Sync(getTableTypeStr(query))
}
func MetaData() {
	Storage.MetaData()
}
